#include <iostream>
#include <string>
#include <curl/curl.h>

std::string api_key = "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";
std::string endpoint = "https://api.openai.com/v1/chat/completions";

curl_mime *curl_mime_init(CURL *easy_handle);

// 处理响应回调函数
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

int main() {
    // 初始化libcurl
    CURL* curl;
    CURLcode res;
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    
    if(curl) {
        std::string response_string;
        std::string json_payload = R"({
            "model": "gpt-4",
            "messages": [{"role": "user", "content": "你好，ChatGPT!"}]
        })";
        struct curl_slist* headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        headers = curl_slist_append(headers, ("Authorization: Bearer " + api_key).c_str());

        curl_easy_setopt(curl, CURLOPT_URL, endpoint.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_payload.c_str());
        
        // 设置写入回调函数
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string);

        // 发送请求
        res = curl_easy_perform(curl);
        
        // 检查请求是否成功
        if(res != CURLE_OK) {
            std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
        } 
        else {
            std::cout << "Response from API: " << response_string << std::endl;
        }

        // 清理
        curl_easy_cleanup(curl);
        curl_slist_free_all(headers);
    }

    curl_global_cleanup();
    return 0;
}